<template>
  <div class="app-container">
    <el-row class='select-row'>
      <el-col :span='24'>
        <p class='title'>{{$t('parameter.settings.first')}}</p>
        <el-form :model='form' label-width="100px" ref='selectForm' label-position="top" inline class='selectForm' :rules="formRules">
          <el-form-item :label="$t('parameter.settings.deviceTypeId')" prop="deviceTypeId">
            <el-select @change="deviceTypeChange" v-model="form.deviceTypeId" clearable size="middle" style="width: 240px">
              <el-option v-for="dict in deviceTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('parameter.settings.deviceModelId')" prop="deviceModelId">
            <el-select  @change="deviceModelChange" v-model="form.deviceModelId" clearable size="middle" style="width: 240px">
              <el-option v-for="dict in deviceModelOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('parameter.settings.taskName')" prop="taskName">
            <el-input v-model="form.taskName" clearbale size="middle" style="width: 240px">
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('parameter.settings.remark')" prop="remark">
            <el-input v-model="form.remark" clearable size="middle" style="width: 240px">
            </el-input>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-row class='select2-row'>
      <el-col :span='12' class='mr20'>
        <div class='title flex'>
          <span>{{$t('parameter.settings.second')}}</span>
          <span class='link-type'>{{$t('parameter.settings.selectedDevice')}}：{{deviceList.length}}</span>
          <el-button v-if='deviceList.length' type="text" plain icon="el-icon-edit" size="mini"
                     @click="showDeviceDialog = true"
                     v-hasPermi="['system:user:import']">
            {{$t('common.button.edit')}}
          </el-button>
        </div>
        <div :class="!deviceList.length ? 'second-wrap' : 'second-wrap2'">
          <i v-if='!deviceList.length' class='el-icon-plus' @click='handleAddDevice'></i>
          <el-table v-else :data="deviceList">
            <el-table-column :show-overflow-tooltip="true" align="center" prop="deviceCode" :label="$t('parameter.settings.deviceCode')" width="150" />
            <el-table-column :show-overflow-tooltip="true" align="center" prop="softwareVersion" :label="$t('parameter.settings.softwareVersion')" width="200" />
            <el-table-column :show-overflow-tooltip="true" align="center" prop="deviceTypeName" :label="$t('parameter.settings.deviceTypeName')" />
            <el-table-column :show-overflow-tooltip="true" align="center" prop="deviceModelName" :label="$t('parameter.settings.deviceModelName')" />
            <el-table-column :show-overflow-tooltip="true" align="center" prop="userCode" :label="$t('parameter.settings.userCode')" width="150"  />
            <el-table-column :show-overflow-tooltip="true" align="center" prop="vehicleNick" :label="$t('parameter.settings.vehicleNick')" width="150"  />
          </el-table>
        </div>
      </el-col>

      <el-col :span='12'>
        <div class='title'><span>{{$t('parameter.settings.third')}}</span></div>
        <el-table border :data="paramList" :loading='paramLoading' height="calc(100% - 60px)" style="width: 100%" @selection-change="handleSelectChange">
          <el-table-column fixed type="selection" label="" width='50px'></el-table-column>
          <el-table-column show-overflow-tooltip prop="paramLabelZhCn" v-if="language === 'zh_CN'" :label="$t('parameter.settings.paramLabel')" width='200px'></el-table-column>
          <el-table-column show-overflow-tooltip prop="paramLabelEnUs"  v-else-if="language === 'en_US'" :label="$t('parameter.settings.paramLabel')" width='200px'></el-table-column>
          <el-table-column show-overflow-tooltip prop="paramLabel" v-else :label="$t('parameter.settings.paramLabel')" width='200px'></el-table-column>

          <el-table-column show-overflow-tooltip prop="paramValue" :label="$t('parameter.settings.paramValue')" width='200px'>
            <template slot-scope='scope'>
              <el-input @change='paramsValidate(scope.row)' v-if='scope.row.paramInput === 1' @input="onInput(scope.row)"
                        :disabled='scope.row.disabled' v-model='scope.row.paramDefault'></el-input>

              <el-input @change='paramsValidate(scope.row)' v-else-if='scope.row.paramInput === 2'
                        :disabled='scope.row.disabled' v-model='scope.row.paramDefault'></el-input>

              <el-select v-else-if='scope.row.paramInput === 3' v-model="scope.row.paramDefault" placeholder="" :disabled='scope.row.disabled'>
                <el-option v-for="item in scope.row.options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
              <!-- <el-select v-else-if='scope.row.paramInput === 4' v-model="scope.row.paramDefault" placeholder="" :disabled='scope.row.disabled'>
                <el-option v-for="item in scope.row.options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select> -->
              <!-- <el-select v-else-if='scope.row.paramInput === 4' v-model="scope.row.paramDefault" placeholder="" :disabled='scope.row.disabled'>
                <el-option v-for="item in scope.row.options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select> -->
            </template>
          </el-table-column>

          <el-table-column show-overflow-tooltip prop="remarkZhCn" v-if="language === 'zh_CN'" :label="$t('parameter.settings.paramRemark')" width='575px'></el-table-column>
          <el-table-column show-overflow-tooltip prop="remarkEnUs"  v-else-if="language === 'en_US'" :label="$t('parameter.settings.paramRemark')" width='575px'></el-table-column>
          <el-table-column show-overflow-tooltip prop="remark" v-else :label="$t('parameter.settings.paramRemark')" width='575px'></el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <div class='add-footer'>
      <el-button type='primary' @click="handleSet" :disabled='disabled'  v-hasPermi="['parameter:settingsTask:add']">{{$t('parameter.settings.issue')}}</el-button>
    </div>

    <DeviceDialog :params='dialogParams' :deviceList='deviceList'
                  :dialogVisible.sync='showDeviceDialog' @selection='handleSelection'
                  @close='showDeviceDialog = false' />

  </div>
</template>

<script>
import DeviceDialog from '@/views/ota/upgrade/modules/DeviceDialog';
import { typeTree } from "@/api/device/type";
import { modelTree } from "@/api/device/model";
import { getCommandParams } from "@/api/parameter/item";
import { getLanguage } from "@/utils/auth";
import { addCommandTask } from "@/api/parameter/settings";

export default {
  name: "index",
  components: {
    DeviceDialog
  },
  data() {
    return {
      deviceTypeOptions: [],
      deviceModelOptions: [],
      form: {
        deviceTypeId: undefined,
        deviceModelId: undefined,
        devices: [],
        params: [],
        commandType: 2, // 1参数查询,2参数下发
        remark: '',
        taskName: ''
      },
      formRules: {
        deviceTypeId: [
          {required: true, message: this.$t('parameter.settings.rules.deviceTypeId'), trigger: 'change'}
        ],
        deviceModelId: [
          {required: true, message: this.$t('parameter.settings.rules.deviceModelId'), trigger: 'change'}
        ],
        taskName: [
          {required: true, message: this.$t('parameter.settings.rules.taskName'), trigger: 'change'}
        ]
      },
      deviceList: [],
      modelOptions: [],
      paramList: [],
      showDeviceDialog: false,
      paramLoading: false,
      selectedParams: [],
      isValidate: false
    }
  },
  computed: {
    language() {
      return getLanguage()
    },
    disabled() {
      if (this.form.deviceTypeId && this.form.deviceModelId && this.form.taskName &&
        this.form.devices.length > 0 && this.selectedParams.length > 0) {
        return false
      } else {
        return true
      }
    },
    dialogParams() {
      return { deviceTypeId: this.form.deviceTypeId, deviceModelId: this.form.deviceModelId }
    }
  },
  created() {
    this.getTypeTree();
  },
  methods: {
    onInput(row) {
      // 移除非数字和小数点字符
      row.paramDefault = row.paramDefault.replace(/[^\d.]/g, '');

      // 限制小数位数为四位
      const parts = row.paramDefault.split('.');
      if (parts.length > 1) {
        const decimal = parts[1].slice(0, 4);
        row.paramDefault = parts[0] + '.' + decimal;
      }
    },
    deviceTypeChange(typeId) {
      if (typeId) {
        this.getModelTree(typeId)
      } else {
        this.form.deviceModelId = undefined
        this.deviceModelOptions = []
      }
    },
    deviceModelChange(modelId) {
      modelId && this.getParamList()
    },
    getTypeTree() {
      typeTree().then(response => {
        this.deviceTypeOptions = response.data;
      });
    },
    getModelTree(typeId) {
      modelTree(typeId).then(response => {
        this.deviceModelOptions = response.data;
      });
    },
    handleAddDevice() {
      if (this.form.deviceTypeId && this.form.deviceModelId) {
        this.showDeviceDialog = true;
      } else {
        this.$alert(this.$t('parameter.settings.typeFirst'), this.$t('common.prompt.tip'), {
          confirmButtonText: this.$t('common.button.confirm'),
          callback: action => { }
        });
      }
    },
    handleSelection(list) {
      this.deviceList = list;
      this.form.devices = list.map(item => {
        return item.deviceCode
      });
    },
    getParamList() {
      const params = {
        deviceTypeId: this.form.deviceTypeId,
        deviceModelId: this.form.deviceModelId,
        commandType: 2,//1参数查询,2参数下发
      }
      this.paramLoading = true;
      getCommandParams(params).then(res => {
        this.paramList = res.data;
        this.paramList.forEach(item => {
          //选择框
          let options = [];
          if (item.paramInput === 3) {

            let limitReg;
            if (this.language === 'zh_CN') {
              limitReg = item.limitRegZhCn.split(',');
            } else if(this.language === 'en_US') {
              limitReg = item.limitRegEnUs.split(',');
            } else {
              limitReg = item.limitReg.split(',');
            }

            // let m = item.limitReg.split(',');
            limitReg.forEach((item1, index) => {
              options.push({
                value: item1.split(':')[0],
                label: item1.split(':')[1]
              });
            });
            if (item.paramValue === undefined || item.paramValue === null || item.paramValue === '') {
              this.$set(item, 'paramValue', item.paramDefault);
            }
            this.$set(item, 'defaultValue', item.paramDefault);
          }
          this.$set(item, 'options', options)
          this.$set(item, 'disabled', true)
        })
        this.paramLoading = false

      })
    },
    handleSelectChange(row) {
      row.forEach(item => {
        item.disabled = false
      })
      this.selectedParams = row
    },
    handleSet() {
      this.form.params = this.selectedParams.map(item => {
        return {
          type: item.paramValue,
          value: item.paramDefault
        }
      })

      addCommandTask(this.form).then(res => {
        if (res.code === 200) {
          this.$modal.addSuccess();
          // 跳转列表
          const obj = { path: "/parameter/settingsTask" };
          this.$tab.closeOpenPage(obj);
        }
      }).catch(err => {
        this.$message.error(err.msg);
      })
    },
    paramsValidate(params) {
      let limitReg;
      let msgWarning;
      if (this.language === 'zh_CN') {
        msgWarning = params.remarkZhCn
        limitReg = params.limitRegZhCn.split('-');
      } else if(this.language === 'en_US') {
        msgWarning = params.remarkEnUs
        limitReg = params.limitRegEnUs.split('-');
      } else {
        msgWarning = params.remark
        limitReg = params.limitReg.split('-');
      }

      let value = params.paramDefault;
      if (value < parseInt(limitReg[0]) || value > parseInt(limitReg[1])) {
        this.$modal.msgWarning(msgWarning)
        this.isValidate = false;
      } else {
        this.isValidate = true;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  border-bottom: 1px solid #ccc;
  margin: 0 0 10px 0;
  padding-bottom: 20px;
  text-align: left;
  font-size: 14px;
}
.select-row {
  background: #fff;
  padding: 20px;
  margin-bottom: 30px;
}
.select2-row {
  margin: 0;
  display: flex;
  justify-content: space-between;
  .el-col-12 {
    background: #fff;
    padding: 20px;
    height: 52vh;
  }
}
.el-form-item {
  width: 300px;
}
.add-footer {
  display: flex;
  justify-content: flex-end;
  padding: 30px 0;
}
.flex {
  display: flex;
  justify-content: space-between;
}
.second-wrap {
  height: calc(100% - 60px);
  display: flex;
  justify-content: center;
  align-items: center;
  .el-icon-plus {
    font-size: 32px;
    cursor: pointer;
  }
}
.second-wrap2 {
  height: calc(100% - 60px);
  overflow: auto;
}
</style>
